package com.smile.frame.api.es.service.impl;

import cn.hutool.json.JSONUtil;
import com.smile.frame.api.es.document.Order;
import com.smile.frame.api.es.service.IEsOrderService;
import com.smile.frame.common.exception.BizException;
import com.smile.frame.config.es.constants.EsIndexNameConstant;
import com.smile.frame.config.es.service.IEsService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author LGC
 */
@Slf4j
@Service
public class EsOrderServiceImpl implements IEsOrderService {
    private final static String INDEX_NAME = EsIndexNameConstant.ORDER_INDEX;

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private IEsService esService;

    @Override
    public Boolean insertOrder(Order order) {
        log.info("插入订单文档 doc:{}", order);
        try {
            if (!esService.isIndexExist(INDEX_NAME)) {
                esService.createIndex(INDEX_NAME);
            }
            BulkRequest bulkRequest = new BulkRequest();
            // code做为索引的id
            IndexRequest indexRequest = new IndexRequest(INDEX_NAME)
                    .id(String.valueOf(order.getOrderSn()))
                    .source(JSONUtil.toJsonStr(order), XContentType.JSON);
            bulkRequest.add(indexRequest);

            BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            if (bulkResponse.hasFailures()) {
                throw new BizException("插入订单文档失败");
            }
        } catch (IOException e) {
            log.error("插入订单文档异常", e);
            return false;
        }
        return true;
    }
}
